﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using ProjectFootball.MVC.Models.EntityFramework.Contexts;
using ProjectFootball.MVC.Models.EntityFramework.Entities;

namespace ProjectFootball.MVC.Foundation.Repositories
{
    public class DataRepository<T> : IDataRepository<T>
        where T : class
    {
        PFDBContext context;
        DbSet<T> dbSet;

        public DataRepository()
            : this(new PFDBContext())
        {
        }

        public DataRepository(PFDBContext context)
        {
            this.context = context;
            dbSet = context.Set<T>();
        }

        public void Add(T entity)
        {
            dbSet.Add(entity);
        }

        public void AddAll(IEnumerable<T> entities)
        {
            foreach (T entity in entities)
                Add(entity);
        }

        public void Remove(T entity)
        {
            dbSet.Remove(entity);
        }

        public void RemoveAll(IEnumerable<T> entities)
        {
            foreach (T entity in entities)
                Remove(entity);
        }

        public IQueryable<T> Where(Expression<Func<T, bool>> predicate)
        {
            return dbSet.Where(predicate);
        }

        public IQueryable<T> Where(Expression<Func<T, bool>> predicate, string include)
        {
            return DoIncludes(this.dbSet, include).Where(predicate);
        }

        public IQueryable<T> Where(Expression<Func<T, bool>> predicate, string[] include)
        {
            return DoIncludes(this.dbSet, include).Where(predicate);
        }

        public IQueryable<T> All()
        {
            return dbSet;
        }

        public IQueryable<T> All(string include)
        {
            return DoIncludes(this.dbSet, include);
        }

        public IQueryable<T> All(string[] include)
        {
            return DoIncludes(this.dbSet, include);
        }

        private static IQueryable<T> DoIncludes(IQueryable<T> query, string include)
        {
            return query.Include(include);
        }

        private static IQueryable<T> DoIncludes(IQueryable<T> query, string[] include)
        {
            foreach (string inc in include)
                query = query.Include(inc);

            return query;
        }

        
    }
}